<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的个人博客</title>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --text-color: #333;
            --text-light: #777;
            --border-radius: 8px;
            --box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: #f9f9f9;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* 导航栏样式 */
        header {
            background-color: var(--secondary-color);
            color: white;
            padding: 1rem 0;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: var(--box-shadow);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 1.8rem;
            font-weight: bold;
            color: white;
            text-decoration: none;
        }

        nav ul {
            display: flex;
            list-style: none;
        }

        nav ul li {
            margin-left: 1.5rem;
        }

        nav ul li a {
            color: white;
            text-decoration: none;
            transition: var(--transition);
            padding: 0.5rem;
            border-radius: var(--border-radius);
        }

        nav ul li a:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        /* 按钮样式 */
        .btn {
            display: inline-block;
            padding: 0.5rem 1.5rem;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            text-decoration: none;
            transition: var(--transition);
            font-size: 1rem;
        }

        .btn:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
        }

        .btn-danger {
            background-color: var(--accent-color);
        }

        .btn-danger:hover {
            background-color: #c0392b;
        }

        .btn-success {
            background-color: var(--success-color);
        }

        .btn-success:hover {
            background-color: #27ae60;
        }

        /* 卡片样式 */
        .card {
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            transition: var(--transition);
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: 1rem;
            transition: var(--transition);
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        textarea.form-control {
            min-height: 200px;
            resize: vertical;
        }

        /* 页面内容区域 */
        .main-content {
            padding: 2rem 0;
            min-height: calc(100vh - 200px);
        }

        /* 文章列表 */
        .article-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
        }

        .article-card {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .article-card img {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: var(--border-radius) var(--border-radius) 0 0;
        }

        .article-card-content {
            padding: 1.5rem;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .article-card h3 {
            margin-bottom: 0.5rem;
            color: var(--secondary-color);
        }

        .article-meta {
            color: var(--text-light);
            font-size: 0.9rem;
            margin-bottom: 1rem;
        }

        .article-excerpt {
            margin-bottom: 1rem;
            flex-grow: 1;
        }

        /* 登录页面 */
        .login-container {
            max-width: 400px;
            margin: 2rem auto;
            padding: 2rem;
        }

        /* 页脚样式 */
        footer {
            background-color: var(--dark-color);
            color: white;
            padding: 2rem 0;
            text-align: center;
        }

        /* 工具类 */
        .text-center {
            text-align: center;
        }

        .mt-1 { margin-top: 0.5rem; }
        .mt-2 { margin-top: 1rem; }
        .mt-3 { margin-top: 1.5rem; }
        .mt-4 { margin-top: 2rem; }

        .hidden {
            display: none;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            nav ul {
                margin-top: 1rem;
                justify-content: center;
            }
            
            nav ul li {
                margin: 0 0.5rem;
            }
            
            .article-list {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <header>
        <div class="container header-content">
            <a href="#" class="logo">我的博客</a>
            <nav>
                <ul>
                    <li><a href="#" onclick="showPage('home')">首页</a></li>
                    <li><a href="#" onclick="showPage('articles')">文章</a></li>
                    <li><a href="#" onclick="showPage('files')">文件</a></li>
                    <li id="login-nav-item"><a href="#" onclick="showPage('login')">登录</a></li>
                    <li id="admin-nav-item" class="hidden"><a href="#" onclick="showPage('admin')">管理</a></li>
                    <li id="logout-nav-item" class="hidden"><a href="#" onclick="logout()">退出</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <!-- 主内容区域 -->
    <div class="container main-content">
        <!-- 首页 -->
        <div id="home-page">
            <div class="card text-center">
                <h1>欢迎来到我的个人博客</h1>
                <p class="mt-2">这里记录我的思考、学习和创作</p>
                <div class="mt-3">
                    <a href="#" class="btn" onclick="showPage('articles')">浏览文章</a>
                </div>
            </div>
            
            <h2 class="mt-4">最新文章</h2>
            <div class="article-list mt-2" id="featured-articles">
                <!-- 动态生成的文章卡片 -->
            </div>
        </div>

        <!-- 文章列表页 -->
        <div id="articles-page" class="hidden">
            <h1>所有文章</h1>
            <div class="article-list mt-2" id="all-articles">
                <!-- 动态生成的文章卡片 -->
            </div>
        </div>

        <!-- 文章详情页 -->
        <div id="article-detail-page" class="hidden">
            <article class="card">
                <h1 id="article-title"></h1>
                <div class="article-meta">
                    发布于 <span id="article-date"></span> | 
                    分类: <span id="article-category"></span> |
                    阅读: <span id="article-views"></span>
                </div>
                <div id="article-content" class="mt-2"></div>
            </article>
            <div class="mt-2">
                <a href="#" class="btn" onclick="showPage('articles')">返回列表</a>
            </div>
        </div>

        <!-- 文件管理页 -->
        <div id="files-page" class="hidden">
            <h1>文件管理</h1>
            <div class="card mt-2">
                <h2>上传新文件</h2>
                <form id="upload-form" class="mt-2">
                    <div class="form-group">
                        <input type="file" id="file-input" class="form-control">
                    </div>
                    <button type="submit" class="btn">上传文件</button>
                </form>
            </div>
            
            <div class="card mt-2">
                <h2>文件列表</h2>
                <div class="mt-2" id="file-list">
                    <!-- 动态生成的文件列表 -->
                </div>
            </div>
        </div>

        <!-- 登录页 -->
        <div id="login-page" class="hidden">
            <div class="card login-container">
                <h2 class="text-center">用户登录</h2>
                <form id="login-form" class="mt-2">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <input type="password" id="password" class="form-control" required>
                    </div>
                    <button type="submit" class="btn" style="width: 100%">登录</button>
                </form>
            </div>
        </div>

        <!-- 管理后台 -->
        <div id="admin-page" class="hidden">
            <h1>博客管理</h1>
            
            <div class="card mt-2">
                <h2>创建新文章</h2>
                <form id="create-article-form" class="mt-2">
                    <div class="form-group">
                        <label for="article-title-input">标题</label>
                        <input type="text" id="article-title-input" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="article-category">分类</label>
                        <input type="text" id="article-category" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="article-content-input">内容</label>
                        <textarea id="article-content-input" class="form-control" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="article-cover">封面图片（可选）</label>
                        <input type="file" id="article-cover" class="form-control">
                    </div>
                    <button type="submit" class="btn">发布文章</button>
                </form>
            </div>
            
            <div class="card mt-2">
                <h2>管理现有文章</h2>
                <div class="mt-2" id="admin-article-list">
                    <!-- 动态生成的管理文章列表 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer>
        <div class="container">
            <p>&copy; 2023 我的个人博客. 保留所有权利.</p>
        </div>
    </footer>

    <script>
        // 全局变量
        let currentUser = null;
        var currentToken = null;
        let articles = [];
        let files = [];

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查本地存储中是否有token
            const savedToken = localStorage.getItem('blogToken');
            if (savedToken) {
                currentToken = savedToken;
                validateToken();
            }
            
            // 绑定表单提交事件
            document.getElementById('login-form').addEventListener('submit', handleLogin);
            document.getElementById('upload-form').addEventListener('submit', handleFileUpload);
            document.getElementById('create-article-form').addEventListener('submit', handleCreateArticle);
            
            // 加载初始数据
            loadArticles();
            loadFiles();
            
            // 显示首页
            showPage('home');
        });

        // 显示指定页面
        function showPage(pageId) {
            // 隐藏所有页面
            document.querySelectorAll('.main-content > div').forEach(page => {
                page.classList.add('hidden');
            });
            
            // 显示请求的页面
            document.getElementById(`${pageId}-page`).classList.remove('hidden');
            
            // 特殊处理
            if (pageId === 'articles') {
                loadArticles();
            } else if (pageId === 'files') {
                loadFiles();
            } else if (pageId === 'admin') {
                loadArticlesForAdmin();
            }
        }

        // 登录处理
        async function handleLogin(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            try {
                const response = await fetch('http://localhost:3300/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    currentToken = data.data.token;
                    localStorage.setItem('blogToken', currentToken);
                    
                    // 更新UI
                    updateAuthUI(true);
                    showPage('home');
                } else {
                    alert('登录失败: ' + data.error);
                }
            } catch (error) {
                console.error('登录错误:', error);
                alert('登录过程中发生错误');
            }
        }

        // 验证token
        async function validateToken() {
            try {
                const response = await fetch('http://localhost:3300/api/auth/check', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    }
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    currentUser = { username: 'admin' }; // 简化处理，实际应从token解码
                    updateAuthUI(true);
                } else {
                    localStorage.removeItem('blogToken');
                    currentToken = null;
                    updateAuthUI(false);
                }
            } catch (error) {
                console.error('Token验证错误:', error);
                localStorage.removeItem('blogToken');
                currentToken = null;
                updateAuthUI(false);
            }
        }

        // 更新认证相关的UI
        function updateAuthUI(isLoggedIn) {
            if (isLoggedIn) {
                document.getElementById('login-nav-item').classList.add('hidden');
                document.getElementById('admin-nav-item').classList.remove('hidden');
                document.getElementById('logout-nav-item').classList.remove('hidden');
            } else {
                document.getElementById('login-nav-item').classList.remove('hidden');
                document.getElementById('admin-nav-item').classList.add('hidden');
                document.getElementById('logout-nav-item').classList.add('hidden');
            }
        }

        // 退出登录
        function logout() {
            currentToken = null;
            currentUser = null;
            localStorage.removeItem('blogToken');
            updateAuthUI(false);
            showPage('home');
        }

        // 加载文章列表
        async function loadArticles() {
            try {
                const response = await fetch('http://localhost:3300/api/articles', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    },
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    articles = data.data;
                    renderArticles(articles, 'all-articles');
                    renderArticles(articles.slice(0, 3), 'featured-articles'); // 首页只显示3篇
                } else {
                    console.error('加载文章失败:', data.message);
                }
            } catch (error) {
                console.error('加载文章错误:', error);
            }
        }

        // 渲染文章列表
        function renderArticles(articles, containerId) {
            const container = document.getElementById(containerId);
            container.innerHTML = '';
            
            if (articles.length === 0) {
                container.innerHTML = '<p>暂无文章</p>';
                return;
            }
            
            articles.forEach(article => {
                const articleCard = document.createElement('div');
                articleCard.className = 'card article-card';
                
                // 截取文章前100字作为摘要
                const excerpt = article.content.length > 100 ? 
                    article.content.substring(0, 100) + '...' : article.content;
                
                articleCard.innerHTML = `
                    ${article.coverImage ? `<img src="http://localhost:3300${article.coverImage}" alt="${article.title}">` : ''}
                    <div class="article-card-content">
                        <h3>${article.title}</h3>
                        <div class="article-meta">
                            ${new Date(article.createTime).toLocaleDateString()} | 
                            ${article.category}
                        </div>
                        <div class="article-excerpt">${excerpt}</div>
                        <a href="#" class="btn mt-1" onclick="showArticleDetail('${article.id}')">阅读更多</a>
                    </div>
                `;
                
                container.appendChild(articleCard);
            });
        }

        // 显示文章详情
        function showArticleDetail(articleId) {
            const article = articles.find(a => a.id === articleId);
            if (!article) return;
            
            document.getElementById('article-title').textContent = article.title;
            document.getElementById('article-date').textContent = new Date(article.createTime).toLocaleDateString();
            document.getElementById('article-category').textContent = article.category;
            document.getElementById('article-views').textContent = article.views || 0;
            document.getElementById('article-content').textContent = article.content;
            
            showPage('article-detail');
        }

        // 加载文件列表
        async function loadFiles() {
            try {
                const response = await fetch('http://localhost:3300/api/listFiles', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    },
                    body: formData
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    files = data.data;
                    renderFiles(files);
                } else {
                    console.error('加载文件失败:', data.message);
                }
            } catch (error) {
                console.error('加载文件错误:', error);
            }
        }

        // 渲染文件列表
        function renderFiles(files) {
            const container = document.getElementById('file-list');
            container.innerHTML = '';
            
            if (files.length === 0) {
                container.innerHTML = '<p>暂无文件</p>';
                return;
            }
            
            const fileList = document.createElement('ul');
            fileList.style.listStyle = 'none';
            
            files.forEach(file => {
                const listItem = document.createElement('li');
                listItem.style.padding = '0.5rem 0';
                listItem.style.borderBottom = '1px solid #eee';
                
                listItem.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span>${file}</span>
                        <div>
                            <a href="/file/user_files/${file}" class="btn" download>下载</a>
                            <button class="btn btn-danger" onclick="deleteFile('${file}')">删除</button>
                        </div>
                    </div>
                `;
                
                fileList.appendChild(listItem);
            });
            
            container.appendChild(fileList);
        }

        // 上传文件处理
        async function handleFileUpload(e) {
            e.preventDefault();
            
            if (!currentToken) {
                alert('请先登录');
                return;
            }
            
            const fileInput = document.getElementById('file-input');
            if (!fileInput.files.length) {
                alert('请选择文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            try {
                const response = await fetch('http://localhost:3300/api/upload', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    },
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('文件上传成功');
                    fileInput.value = '';
                    loadFiles(); // 刷新文件列表
                } else {
                    alert('文件上传失败');
                }
            } catch (error) {
                console.error('文件上传错误:', error);
                alert('文件上传过程中发生错误');
            }
        }

        // 删除文件
        async function deleteFile(filename) {
            if (!confirm(`确定要删除文件 "${filename}" 吗？`)) return;
            
            // 注意：这里需要实现删除文件的API，当前代码中没有删除API
            // 这里只是示例，实际需要后端支持
            alert('删除文件功能需要后端API支持');
        }

        // 创建新文章
        async function handleCreateArticle(e) {
            e.preventDefault();
            
            if (!currentToken) {
                alert('请先登录');
                return;
            }
            console.log('currentToken',currentToken)
            const title = document.getElementById('article-title-input').value;
            const category = document.getElementById('article-category').value;
            const content = document.getElementById('article-content-input').value;
            const coverImage = document.getElementById('article-cover').files[0];
            
            const formData = new FormData();
            formData.append('title', title);
            formData.append('category', category);
            formData.append('content', content);
            if (coverImage) {
                formData.append('coverImage', coverImage);
            }
            
            try {
                const response = await fetch('http://localhost:3300/api/articles', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${currentToken}`
                    },
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    alert('文章发布成功');
                    document.getElementById('create-article-form').reset();
                    loadArticles(); // 刷新文章列表
                } else {
                    alert('文章发布失败: ' + data.message);
                }
            } catch (error) {
                console.error('发布文章错误:', error);
                alert('发布文章过程中发生错误');
            }
        }

        // 加载管理文章列表
        async function loadArticlesForAdmin() {
            // 复用普通文章加载，但增加管理操作按钮
            await loadArticles();
            
            const container = document.getElementById('admin-article-list');
            if (articles.length === 0) {
                container.innerHTML = '<p>暂无文章</p>';
                return;
            }
            
            const articleList = document.createElement('ul');
            articleList.style.listStyle = 'none';
            
            articles.forEach(article => {
                const listItem = document.createElement('li');
                listItem.style.padding = '0.5rem 0';
                listItem.style.borderBottom = '1px solid #eee';
                
                listItem.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin: 0">${article.title}</h3>
                            <small>${new Date(article.createTime).toLocaleDateString()} | ${article.category}</small>
                        </div>
                        <div>
                            <button class="btn" onclick="editArticle('${article.id}')">编辑</button>
                            <button class="btn btn-danger" onclick="deleteArticle('${article.id}')">删除</button>
                        </div>
                    </div>
                `;
                
                articleList.appendChild(listItem);
            });
            
            container.innerHTML = '';
            container.appendChild(articleList);
        }

        // 编辑文章（示例）
        function editArticle(articleId) {
            alert('编辑文章功能待实现: ' + articleId);
        }

        // 删除文章（示例）
        function deleteArticle(articleId) {
            if (!confirm('确定要删除这篇文章吗？此操作不可恢复。')) return;
            
            // 注意：这里需要实现删除文章的API，当前代码中没有删除API
            // 这里只是示例，实际需要后端支持
            alert('删除文章功能需要后端API支持');
        }
    </script>
</body>
</html>